<template>
  <div class="register-form">
    <p class="register-form-logo">注册账号</p>
    <el-form
      :model="form"
      ref="form"
      :rules="rule"
      status-icon
      label-width="95px"
      label-position="right"
    >
      <el-form-item prop="username" label="用户名">
        <el-input v-model="form.username" @blur="checkName"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="关联手机号">
        <el-input v-model="form.phone" @blur="checkPhone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="设置密码">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item prop="captcha" label="验证码">
        <el-input v-model="form.captcha" style="width:150px;margin-right: 20px;"></el-input>
        <el-button
          type="primary"
          :disabled="codeLoading"
          :loading="codeLoading"
          @click="sendCaptcha()"
        >{{count<60?`(${count})s重新获取`:'获取验证码'}}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="backLogin">返回</el-button>
        <el-button
          type="primary"
          :disabled="submitLoading"
          :loading="submitLoading"
          @click="submitRegister('form')"
        >提交</el-button>
        <!-- <el-button type="primary" @click="reset">清空</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userAPI } from "@/utils/api.js";
export default {
  data() {
    return {
      codeLoading: false, //点击获取验证码显示加载中 并禁用
      submitLoading: false, //点击提交显示加载中,并禁用
      count: 60, //重新获取验证码倒计时
      /* 重置密码表单 */
      form: {
        username: "", //用户名
        phone: "", //手机号
        captcha: "", //验证码
        password: "" //设置密码
      },
      //表单验证规则
      rule: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            max: 20,
            min: 2,
            message: "用户名长度限制为2-20位",
            trigger: "blur"
          },
          {
            pattern: /^(?![_\-])(?![0-9]+$)[a-zA-Z0-9_\-\u4e00-\u9fa5]{2,20}$/, //用户名正则
            message:
              "用户名只包含数字、字母、中文和_-，且不能为纯数字和以_-开头",
            trigger: "blur"
          }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^[1][3,4,5,7,8][0-9]{9}$/, //手机号正则
            message: "手机号格式不正确，请输入11位手机号",
            trigger: "blur"
          }
        ],
        captcha: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { max: 4, min: 4, message: "验证码长度限制为4位", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请设置密码", trigger: "blur" },
          { max: 16, min: 6, message: "密码长度限制为6-16位", trigger: "blur" },
          {
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, //密码正则
            message: "密码必须包含字母和数字",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    backLogin() {
      //返回登录表单
      //this.$refs["form"].resetFields();
      this.$emit("backLogin");
    },
    checkName() {
      //检查用户名唯一性
      this.$refs["form"].validateField("username", error => {
        if (!error) {
          this.submitLoading = true;
          let data = { name: this.form.username };
          userAPI.register
            .nameCheck(data)
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
              if (res.code == 7) {
                this.$message.error("用户名已存在，请重新输入");
                this.$refs["form"].clearValidate();
                this.$set(this.form, "username", "");
              }
            })
            .finally(() => {
              this.submitLoading = false; //取消加载和禁用
            });
        }
      });
    },
    checkPhone() {
      //检查手机号唯一性
      this.$refs["form"].validateField("phone", error => {
        if (!error) {
          this.submitLoading = true;
          let data = { name: this.form.phone };
          userAPI.register
            .phoneCheck(data)
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
              if (res.code == 7) {
                this.$message.error("手机号已存在，请重新输入");
                this.$refs.form.clearValidate();
                this.$set(this.form, "phone", "");
              }
            })
            .finally(() => {
              this.submitLoading = false; //取消加载和禁用
            });
        }
      });
    },
    sendCaptcha() {
      //获取验证码
      this.$refs["form"].validateField("phone", error => {
        if (!error) {
          this.codeLoading = true;
          let data = {
            captchaType: "REGISTER",
            token: this.form.phone
          };
          userAPI.common
            .getMessageToken(data)
            .then(res => {
              this.startCount();
            })
            .catch(err => {
              console.log(err);
            })
            .finally(() => {
              this.codeLoading = false; //取消加载和禁用
            });
        }
      });
    },
    startCount() {
      this.timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          this.count = 60;
          clearInterval(this.timer);
        }
      }, 1000);
    },
    submitRegister() {
      /* 提交账号表单 */
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.submitLoading = true;
          let data = this.form;
          userAPI.register
            .register(data)
            .then(res => {
              console.log(res);
              this.$message({
                type: "success",
                message: "注册成功,快去登录吧！"
              });
            })
            .catch(err => {
              //console.log(err);
            })
            .finally(() => {
              this.submitLoading = false; //取消加载和禁用
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.register-form {
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 525px;
  padding: 10px 38px;
  box-shadow: rgba(0, 0, 0, 0.3) 0 0 50px;
  border-radius: 3px;
  background-color: #fff;
  animation: register-show 0.5s ease 0.2s forwards;
  .register-form-logo {
    padding: 14px 0;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
@keyframes register-show {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}
</style>